<?php

namespace app\model;

use think\Model;

class Points extends Model
{

    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'points';

    public function member()
    {
        return $this->hasOne(Member::class, 'id', 'uid');
    }

    /**
     * 积分更新
     * @param $params
     * @return void
     */
    public static function uppoints($params)
    {

        $pointsConfig =  Config::getconfig('points');
        $points = $params['points'];

        //更新积分
        if ($points) {
            $uid = (int) $params['uid'];
            $type = (int) $params['type'];
            $order_id = (int) $params['order_id'];
            $order_num_alias = (int) $params['order_num_alias'];
            $description = $params['description'];
            $from_type = $params['from_type'];

            if ($params['create_time']) {
                $create_time = $params['create_time'];
            } else {
                $create_time = time();
            }

//            if (0 < $points && $points < 1) {
//                $points = 1;
//            }

    
            $points = round($points, 2);

            $createdata = [
                'weid' => weid(),
                'uid' => $uid,
                'order_id' => $order_id,
                'order_num_alias' => $order_num_alias,
                'points' => $points,
                'is_staging' => (int) $pointsConfig['is_staging'],
                'description' => $description,
                'prefix' => 1,
                'create_time' => $create_time,
                'type' => $type
            ];
            if(!empty($from_type)){
                $createdata['from_type'] = $from_type;
            }

            if ($pointsConfig['is_staging'] == 1) {
                $createdata['is_staging'] = (int) $pointsConfig['is_staging'];
                if ($pointsConfig['stagingpoints'] > 0) {
                    $createdata['stagingpoints'] = $pointsConfig['stagingpoints'];
                }
                $createdata['notreceived_points'] = $points;
            }

            self::create($createdata);

            if ($pointsConfig['is_staging'] != 1) {
                if($from_type == 2){
                    Member::where('id', $uid)
                        ->inc('notreceived_points', (int) $points)
                        ->update();
                }else{
                    Member::where('id', $uid)
                        ->inc('points', (int) $points)
                        ->update();
                }

            }
        }
    }
}
